package edu.ads.bookloan

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import org.springframework.dao.DataIntegrityViolationException

class InventoryItemController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def filterPaneService
	static navigation = [
		[group:'tabs', action:'index',title:'Inventory Item', order: 0, isVisible: { SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN,ROLE_EMPLOYEE") }]
	]
    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        [inventoryItemInstanceList: InventoryItem.list(params), inventoryItemInstanceTotal: InventoryItem.count()]
    }

    def create() {
        [inventoryItemInstance: new InventoryItem(params)]
    }

    def save() {
        def inventoryItemInstance = new InventoryItem(params)
        if (!inventoryItemInstance.save(flush: true)) {
            render(view: "create", model: [inventoryItemInstance: inventoryItemInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'inventoryItem.label', default: 'InventoryItem'), inventoryItemInstance.id])
        redirect(action: "show", id: inventoryItemInstance.id)
    }
	
	def filter () {
		if(!params.max) params.max = 10
		render( view:'list',
			model:[ inventoryItemInstanceList: filterPaneService.filter( params, InventoryItem ),
			inventoryItemInstanceTotal: filterPaneService.count( params, InventoryItem ),
			filterParams: org.grails.plugin.filterpane.FilterPaneUtils.extractFilterParams(params),
			params:params ] )
	}

    def show(Long id) {
        def inventoryItemInstance = InventoryItem.get(id)
        if (!inventoryItemInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'inventoryItem.label', default: 'InventoryItem'), id])
            redirect(action: "list")
            return
        }

        [inventoryItemInstance: inventoryItemInstance]
    }

    def edit(Long id) {
        def inventoryItemInstance = InventoryItem.get(id)
        if (!inventoryItemInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'inventoryItem.label', default: 'InventoryItem'), id])
            redirect(action: "list")
            return
        }

        [inventoryItemInstance: inventoryItemInstance]
    }

    def update(Long id, Long version) {
        def inventoryItemInstance = InventoryItem.get(id)
        if (!inventoryItemInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'inventoryItem.label', default: 'InventoryItem'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (inventoryItemInstance.version > version) {
                inventoryItemInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'inventoryItem.label', default: 'InventoryItem')] as Object[],
                          "Another user has updated this InventoryItem while you were editing")
                render(view: "edit", model: [inventoryItemInstance: inventoryItemInstance])
                return
            }
        }

        inventoryItemInstance.properties = params

        if (!inventoryItemInstance.save(flush: true)) {
            render(view: "edit", model: [inventoryItemInstance: inventoryItemInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'inventoryItem.label', default: 'InventoryItem'), inventoryItemInstance.id])
        redirect(action: "show", id: inventoryItemInstance.id)
    }

    def delete(Long id) {
        def inventoryItemInstance = InventoryItem.get(id)
        if (!inventoryItemInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'inventoryItem.label', default: 'InventoryItem'), id])
            redirect(action: "list")
            return
        }

        try {
            inventoryItemInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'inventoryItem.label', default: 'InventoryItem'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'inventoryItem.label', default: 'InventoryItem'), id])
            redirect(action: "show", id: id)
        }
    }
	
	def rentBook(){
		
		InventoryItem inventoryItem =  InventoryItem.get(params?.id)
		
		if(inventoryItem.inventoryItemStatus == InventoryItemStatus.findByStatus('Rented')){
			flash.message = "The book is already rented!!!"
			redirect(action: "show", id: params?.id)
		}
		def degrees = inventoryItem.book.degrees
		def persons = Person.where{ degree in degrees }.findAll()
		println persons
		[inventoryItemInstanceId: params?.id, personsList: persons]
	}
	
	def saveBookRent(){
//		Person person = Person.get(params?.personId)
		InventoryItem inventoryItem =  InventoryItem.get(params?.'inventoryItem.id')
//		int rentalDays = Integer.parseInt(((params?.rentalDays) ?: 4))
		LoanHistory loanHistory = new LoanHistory(params) 
		loanHistory.save(failOnError: true)
		flash.message = "Book has been succesfully rented"
		redirect(action: "show", id: loanHistory.inventoryItem.id)
	}
}
